package com.elite.groovy.callback

import com.elite.groovy.util.EliteBean
import com.elite.groovy.kh.KHUtil
import org.apache.commons.logging.Log
import org.apache.commons.logging.LogFactory

import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse
import java.time.LocalDate

/**
 * @use 工单自动抽检
 * @author admin
 */

public class AutoKHNAssign_Work implements ServiceBackInvoke  {
    private static final Log log = LogFactory.getLog(AutoKHNAssign_Work.class);
    private String charset = "utf-8"; //设置字符集
    private int timeout = 100000; //设置请求超时时间
    private int enableSSLflag = 0;

    public String doCallBack(EliteBean eliteBean, HttpServletRequest request, HttpServletResponse response){

        log.debug("----------------------------------工单自动抽检分配启动----------------------------------");
        List KHNAssignList = eliteBean.chaxun_sql("select CHECKGUID,Staffid, Rolegroupid, Mapidlist, BusinessType1, Timetype, Workstarttime, Workendtime, Ratio, Khby, Config_id from khn_spot_check where type = 'workorder' and strattime <= to_char(sysdate,'yyyy-mm-dd') and endtime >= to_char(sysdate,'yyyy-mm-dd')", "dataSource");
        log.debug("执行抽检规则集合：" + KHNAssignList);

        if (KHNAssignList.size() > 0) {
            //20240329同吴晓玲老师沟通：工单类型不需要加抽规则
            //WorkKHNAssign_ADD(eliteBean, KHNAssignList);
            WorkKHNAssign(eliteBean, KHNAssignList);
        }
    }

    /**
     * @use 工单加抽
     * 确保坐席在当月时间内，抽取数量/存在工单天数 至少大于等于1，如果小于1,则需要补抽这个坐席工单
     */
    private static WorkKHNAssign_ADD(EliteBean eliteBean, List KHNAssignList) {

        for (int i = 0; i < KHNAssignList.size(); i++) {

            log.debug("执行抽检规则：" + KHNAssignList[i].get("CHECKGUID"));
            String Checkguid = KHNAssignList[i].get("CHECKGUID"); //抽检规则guid
            String Staffid = KHNAssignList[i].get("Staffid"); //抽取人
            String Rolegroupid = KHNAssignList[i].get("Rolegroupid"); //抽取组
            String Mapidlist = KHNAssignList[i].get("Mapidlist"); //工单类型
            String Businesstype1 = KHNAssignList[i].get("Businesstype1"); //业务类型
            String Workstarttime = KHNAssignList[i].get("Workstarttime"); //入职开始时间
            String Workendtime = KHNAssignList[i].get("Workendtime"); //入职结束时间
            String Ratio = KHNAssignList[i].get("Ratio"); //抽取比例
            String Khby = KHNAssignList[i].get("Khby"); //质检员
            String Config_Id = KHNAssignList[i].get("Config_Id"); //质检计划
            String AutomaticGUID = UUID.randomUUID().toString(); //当前抽检批次GUID

            //质检计划、抽检比例、质检员不为空，执行方法
            if (!Config_Id.equals("") && !Ratio.equals("") && !Khby.equals("")) {

                String WhereCondition = ""; //SQL条件片段
                if (!KHUtil.isNull(Staffid)) { //抽取坐席
                    WhereCondition += " and o.createdby in (" + Staffid + ") ";
                }
                if (!KHUtil.isNull(Rolegroupid)) { //抽取业务组
                    WhereCondition += " and st.title in (" + Rolegroupid + ") ";
                }
                if (!KHUtil.isNull(Mapidlist)) { //工单类型
                    if(Mapidlist != '\'DHBZGD\''){ //标准工单/业务反馈工单
                        WhereCondition += " and o.Map_Id in (" + Mapidlist + ") ";
                    }else{
                        WhereCondition += " and o.Map_Id in (" + Mapidlist + ") and o.curstep_id_map != 'YJPODX' and o.workordertype != '注销报案申请' ";
                    }
                }
                if (!KHUtil.isNull(Businesstype1)) { //业务类型
                    WhereCondition += " and o.workordertype in (" + Businesstype1 + ") ";
                }
                if (!KHUtil.isNull(Workstarttime)) { //入职开始时间
                    WhereCondition += " and trunc(months_between(sysdate,to_date(to_char(employeddate,'yyyymm'),'yyyymm')))> '" + Workstarttime + "' ";
                }
                if (!KHUtil.isNull(Workendtime)) { //入职结束时间
                    WhereCondition += " and trunc(months_between(sysdate,to_date(to_char(employeddate,'yyyymm'),'yyyymm')))< '" + Workendtime + "' ";
                }
                //获取当月1号,加抽不跨月
                //获取当月1号,加抽不跨月
                LocalDate firstDayOfMonth = LocalDate.now().withDayOfMonth(1);  //获取当前日期并设置为1号
                WhereCondition += " and o.CREATEDDATE >= to_date('" + firstDayOfMonth + "','yyyy-MM-DD HH24:mi:ss')";

                //取当月电话数据
                String AssignCountSQL = '''Select o.Createdby,
                                                Sum(Case When Ka.Assignlist_Guid Is Null Then 1 Else 0 End) As Notkhncount, -- 未被质检
                                                Sum(Case When Ka.Assignlist_Guid Is Not Null Then 1 Else 0 End) As Iskhncount, -- 已被质检
                                                Count(Distinct To_Char(o.Createddate, 'yyyy-mm-dd')) As Days -- 存在工单天数
                                            From Objective o
                                                Left Join Khn_Assignlist Ka On o.Objective_Guid = Ka.Relationid1
                                                Left Join Staff St On o.Createdby = St.Staff_Id
                                                Left Join Rolegroup Rg On St.Defaultrolegroup = Rg.Rolegroup_Id
                                            Where 1 = 1
                                                And St.Exemption = 0
                                                And Rg.Rolegrouptype Not In ('D00002', 'D00003')
                                                ''' + WhereCondition + " Group By o.Createdby";

                log.debug("各坐席质检数据SQL:" + AssignCountSQL);
                List AssignCountList = eliteBean.chaxun_sql(AssignCountSQL, "dataSource");

                int iskhncount, days, notkhncount, addkhncount = 0
                String addstaff_id = '';
                //每次更换规则时，初始化质检员取序
                int j = 0;
                for (int i1 = 0; i1 < AssignCountList.size(); i1++) {
                    String ADDWhereCondition = ''; //初始化加抽SQL条件
                    iskhncount = AssignCountList[i1].get("iskhncount"); //已被质检数
                    days = AssignCountList[i1].get("days"); //存在工单天数
                    notkhncount = AssignCountList[i1].get("notkhncount"); // 未被质检
                    addstaff_id = AssignCountList[i1].get("CREATEDBY"); // 加抽坐席
                    //已被质检小于存在工单天数，则未达到每日一单的数量，需补全
                    //已被质检小于电话天数，则未达到每日一通的数量，需补全
                    if (iskhncount < days && notkhncount > 0) {
                        addkhncount = days - iskhncount;

                        //检查加抽数量是否大于未被质检数，则此次未被质检数作为加抽数
                        if (addkhncount > notkhncount) {
                            addkhncount = notkhncount
                        }
                        //拼接加抽SQL
                        ADDWhereCondition += " and o.CREATEDBY='" + addstaff_id + "'";
                        ADDWhereCondition += " and rownum<=" + addkhncount + "";
                        //查询坐席可被加抽分配数据
                        String ADDAssignCountSQL = '''select distinct o.objective_guid,o.CREATEDBY
                                                    from objective o  
                                                      left join KHN_ASSIGNLIST ka on o.objective_guid = KA.RELATIONID1  
                                                      left join staff st on o.CREATEDBY=st.staff_ID
                                                    where 1=1 
                                                     and ka.assignlist_guid is null 
                                                     and st.Exemption = 0 
                                                ''' + WhereCondition + ADDWhereCondition;
                        List ADDAssignCountList = eliteBean.chaxun_sql(ADDAssignCountSQL, "dataSource");

                        //处理质检员为List，并打乱List数据
                        String KhbyArrString = Khby.replace("\"", "");
                        String[] KhbyArr = KhbyArrString.split(",");


                        for (int i2 = 0; i2 < ADDAssignCountList.size(); i2++) {
                            //数据写入准备
                            String ADDASSIGNLIST_GUID = UUID.randomUUID().toString();
                            String ADDrecord_guid = ADDAssignCountList[i2].get("objective_guid"); //取需分配录音ID
                            String ADDstaff_id = ADDAssignCountList[i2].get("CREATEDBY"); //取工单创建坐席
                            //需循环到第几位质检员
                            String KhbyID = KhbyArr[j]
                            //写入加抽数据
                            String[] data = new String[2];
                            data[0] = "insert into KHN_ASSIGNLIST(Automatic_guid,ASSIGNLIST_GUID,KHTYPE,KHCONFIG_ID,KHCONFIGDATE_ID,BUILDDATE,RECORDBY,KHFLAG,RELATIONID1,KHTOBY,KHBY, CHECKGUID)values('" + AutomaticGUID + "','" + ADDASSIGNLIST_GUID + "','0','" + Config_Id + "','',sysdate,'kfstem',0,'" + ADDrecord_guid + "','" + ADDstaff_id + "'," + KhbyID + ",'" + Checkguid + "' )";
                            data[1] = "insert into khn_assignhistory(REC_GUID,ASSIGNLIST_GUID,RECORD_GUID,KHTYPE,KHCONFIG_ID,KHCONFIGDATE_ID,KHGROUP,KHBY,KHTOBY,CREATEDATE,CREATEBY,source, CHECKGUID) select sysguid,ka.assignlist_guid,ka.relationid1,ka.khtype,ka.khconfig_id,ka.khconfigdate_id,ka.khgroup,ka.khby,ka.khtoby,sysdate,ka.RECORDBY,14, ka.CHECKGUID from khn_assignlist ka where ka.ASSIGNLIST_GUID ='" + ADDASSIGNLIST_GUID + "'";

                            int[] dataresult = eliteBean.updateBatch(data, "dataSource");

                            //轮循质检员完成后，重新轮循
                            if (j == KhbyArr.length - 1) {
                                j = 0;
                            } else {
                                j++;
                            }
                        }
                    }
                }
            }
        }
    }

    /**
     * @use 工单自动抽检
     */
    private static WorkKHNAssign(EliteBean eliteBean, List KHNAssignList) {

        for (int i = 0; i < KHNAssignList.size(); i++) {
            log.debug("执行抽检规则：" + KHNAssignList[i].get("CHECKGUID"));
            String Checkguid = KHNAssignList[i].get("CHECKGUID"); //抽检规则guid
            String Rolegroupid = KHNAssignList[i].get("Rolegroupid"); //抽取组
            String Staffid = KHNAssignList[i].get("Staffid"); //抽取人
            String Mapidlist = KHNAssignList[i].get("Mapidlist"); //工单类型
            String Businesstype1 = KHNAssignList[i].get("Businesstype1"); //业务类型
            String Timetype = KHNAssignList[i].get("Timetype"); //时间段
            String Workstarttime = KHNAssignList[i].get("Workstarttime"); //入职开始时间
            String Workendtime = KHNAssignList[i].get("Workendtime"); //入职结束时间
            String Ratio = KHNAssignList[i].get("Ratio"); //抽取比例
            String Khby = KHNAssignList[i].get("Khby"); //质检员
            String Config_Id = KHNAssignList[i].get("Config_Id"); //质检计划
            String AutomaticGUID = UUID.randomUUID().toString(); //当前抽检批次GUID

            //质检计划、抽检比例、质检员不为空，执行方法
            if (!Config_Id.equals("") && !Ratio.equals("") && !Khby.equals("")) {

                String WhereCondition = ""; //SQL条件片段
                if (!KHUtil.isNull(Staffid)) { //抽取坐席
                    WhereCondition += " and o.createdby in (" + Staffid + ") ";
                }
                if (!KHUtil.isNull(Rolegroupid)) { //抽取业务组
                    WhereCondition += " and st.title in (" + Rolegroupid + ") ";
                }
                if (!KHUtil.isNull(Mapidlist)) { //工单类型
                    if(Mapidlist != '\'DHBZGD\''){ //标准工单/业务反馈工单
                        WhereCondition += " and o.Map_Id in (" + Mapidlist + ") ";
                    }else{
                        WhereCondition += " and o.Map_Id in (" + Mapidlist + ") and o.curstep_id_map != 'YJPODX' and o.workordertype != '注销报案申请' ";
                    }
                }
                if (!KHUtil.isNull(Businesstype1)) { //业务类型
                    WhereCondition += " and o.workordertype  in (" + Businesstype1 + ") ";
                }
                if (!KHUtil.isNull(Workstarttime)) { //开始时间段
                    WhereCondition += " and trunc(months_between(sysdate,to_date(to_char(employeddate,'yyyymm'),'yyyymm'))) >= '" + Workstarttime + "' ";
                }
                if (!KHUtil.isNull(Workendtime)) { //入职结束时间
                    WhereCondition += " and trunc(months_between(sysdate,to_date(to_char(employeddate,'yyyymm'),'yyyymm')))< '" + Workendtime + "' ";
                }
                log.debug("【WhereCondition】：" + WhereCondition);

                //取总数
                String AssignCountSQL = '''Select Distinct o.Objective_Guid,o.Createdby,Dense_Rank() Over(Partition By o.Createdby Order By Dbms_Random.Value) As Relationid2
                                            From Objective o
                                                Left Join Khn_Assignlist Ka On o.Objective_Guid = Ka.Relationid1
                                                Left Join Staff St On o.Createdby = St.Staff_Id
                                                Left Join Rolegroup Rg On St.Defaultrolegroup = Rg.Rolegroup_Id
                                            Where 1 = 1
                                                And Ka.Assignlist_Guid Is Null
                                                And St.Exemption = 0
                                                And o.Createddate >= Trunc(Sysdate) - 1
                                                And o.Createddate < Trunc(Sysdate)
                                                And Rg.Rolegrouptype Not In ('D00002', 'D00003')
                                                ''' + WhereCondition;
                log.debug("工单总数SQL:" + AssignCountSQL);
                List AssignCountList = eliteBean.chaxun_sql(AssignCountSQL, "dataSource");
                int RecordCount = AssignCountList.size();
                log.debug("工单总数:" + RecordCount);

                if (RecordCount > 0) {
                    //计算抽检数
                    int AssignCount = (int) ((RecordCount * (Ratio.toInteger() as Number)) / 100);
                    log.debug("工单抽检数:" + AssignCount);

                    //处理质检员为List，并打乱List数据
                    String KhbyArrString = Khby.replace("\"", "");
                    String[] KhbyArr = KhbyArrString.split(",");
                    //KhbyList = Collections.shuffle(KhbyList); //随机打乱顺序
                    //初始化数据
                    int j = 0;
                    int KhbyCount = 0;
                    String objective_guid = "";
                    String staff_id = "";
                    String KhbyID = "";
                    String ASSIGNLIST_GUID = ""; //当前分配GUID
                    String DEFAULTROLEGROUP = "";
                    //轮循分配,先轮循抽检数
                    for (int i1 = 0; i1 < AssignCount; i1++) {

                        ASSIGNLIST_GUID = UUID.randomUUID().toString();
                        objective_guid = AssignCountList[i1].get("objective_guid"); //取需分配工单ID
                        staff_id = AssignCountList[i1].get("createdby"); //取工单坐席
                        //需循环到第几位质检员
                        KhbyID = KhbyArr[j]
                        List DEFAULTROLEGROUPLIST = eliteBean.chaxun_sql("select DEFAULTROLEGROUP from staff where STAFF_ID=" + KhbyID + "", "dataSource");
                        if (DEFAULTROLEGROUPLIST.size() > 0) {
                            DEFAULTROLEGROUP = DEFAULTROLEGROUPLIST.get(0).get("DEFAULTROLEGROUP");
                        }
                        //数据处理
                        String[] data = new String[2];
                        data[0] = "insert into KHN_ASSIGNLIST(Automatic_guid,ASSIGNLIST_GUID,KHTYPE,KHCONFIG_ID,KHCONFIGDATE_ID,BUILDDATE,RECORDBY,KHFLAG,RELATIONID1,KHTOBY,KHBY,CHECKGUID,KHGROUP)values('" + AutomaticGUID + "','" + ASSIGNLIST_GUID + "','0','" + Config_Id + "','',sysdate,'kfstem',0,'" + objective_guid + "','" + staff_id + "'," + KhbyID + ",'" + Checkguid + "','" + DEFAULTROLEGROUP + "' )";

                        data[1] = "insert into khn_assignhistory(REC_GUID,ASSIGNLIST_GUID,RECORD_GUID,KHTYPE,KHCONFIG_ID,KHCONFIGDATE_ID,KHGROUP,KHBY,KHTOBY,CREATEDATE,CREATEBY,source,CHECKGUID) select sysguid,ka.assignlist_guid,ka.relationid1,ka.khtype,ka.khconfig_id,ka.khconfigdate_id,ka.khgroup,ka.khby,ka.khtoby,sysdate,ka.RECORDBY,4, ka.CHECKGUID from khn_assignlist ka where ka.ASSIGNLIST_GUID ='" + ASSIGNLIST_GUID + "'";

                        int[] dataresult = eliteBean.updateBatch(data, "dataSource");

                        //轮循质检员完成后，重新轮循
                        if (j == KhbyArr.length - 1) {
                            j = 0;
                        } else {
                            j++;
                        }
                    }
                }
            }
        }
    }

}
